package com.gmall.product.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gmall.common.result.Result;
import com.gmall.model.product.BaseTrademark;
import com.gmall.product.mapper.BaseTrademarkMapper;
import com.gmall.product.service.cache.BaseTrademarkCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class BaseTrademarkService {


    @Autowired
    BaseTrademarkMapper trademarkMapper;

    @Autowired
    BaseTrademarkCacheService trademarkCacheService;

    public Result<Page<BaseTrademark>> findPage(Long pageNo, Long  pageSize){
        Page<BaseTrademark> page = new Page<>(pageNo,pageSize)  ;

        QueryWrapper<BaseTrademark> queryWrapper = new QueryWrapper<>();
        Page<BaseTrademark> baseTrademarkPage = trademarkMapper.selectPage(page, queryWrapper);

        return Result.ok(baseTrademarkPage);
    }

    public Result<String> save(BaseTrademark baseTrademark) {

        if(baseTrademark!=null && baseTrademark.getId()!=null){
            //修改
            baseTrademark.setUpdateTime(new Date());
            trademarkCacheService.deleteTrademark(baseTrademark.getId());
            trademarkMapper.updateById(baseTrademark);
            trademarkCacheService.deleteTrademark(baseTrademark.getId());
            return Result.ok("修改成功");
        }
        Date now = new Date();
        baseTrademark.setCreateTime(now);
        baseTrademark.setUpdateTime(now);
        baseTrademark.setIsDeleted(0);
        trademarkMapper.insert(baseTrademark);
        return Result.ok("保存成功");
    }

    public Result<String> remove(Long id) {
        trademarkCacheService.deleteTrademark(id);//双删
        trademarkMapper.deleteById(id);
        try {
            Thread.sleep(3000);//给数据库主库向从库同步数据 留时间
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        trademarkCacheService.deleteTrademark(id);
        return Result.ok("删除成功");
    }

    public Result<String> update(BaseTrademark baseTrademark) {

        baseTrademark.setUpdateTime(new Date());
        trademarkMapper.updateById(baseTrademark);
        trademarkCacheService.deleteTrademark(baseTrademark.getId());
        return Result.ok("修改成功");
    }

    public Result<BaseTrademark> get(Long id) {
        //BaseTrademark baseTrademark = trademarkMapper.selectById(id);
        BaseTrademark baseTrademark = trademarkCacheService.getTrademarkById(id);
        return Result.ok(baseTrademark);
    }
}
